const mongoose = require("mongoose");
const News = require('../models/news.models');
const Comment = require('../models/comment.models');
const Cate = require("../models/cate.models");

exports.create = function (req,res,next) {
    const cate = new Cate(req.body);
    cate.save().then(data=>{
        res.json(data);
    });
};

exports.update = function (req,res,next) {
  const id = req.params.id;
  Cate.findByIdAndUpdate(id,{ $set:req.body },{ new:false }).then(data=>{
    res.json(data);//data:更新之前的数据
  })
};

exports.tree = function (req,res,next) {
  const type = req.params.type;
  Cate.find({type:type},function(err,data){
    var rpTree = reverseTree(data,null);
    res.json(rpTree);
  })
};
//新闻删除功能
exports.remove = function(req, res, next) {
  var id = req.params.id;
  var ids = [];
  Cate.findOne({ _id: id }, function(err, doc) {
    if (doc) {
      ids = [doc._id];
      doc.getChildren().then(function(docs) {
        for (var i = 0; i < docs.length; i++) {
          ids.push(docs[i]._id);
        }
        console.log(docs);
        Cate.remove({ _id: { $in: ids } }).then(data => {
          res.json({ status: 200, message: "删除数据成功" });
        });
      });
    }
  });
};

//使用递归实现树--
function reverseTree(data, pid) {
  var result = [],
    temp;

  var data = JSON.parse(JSON.stringify(data)); //将数据模型对象转成字符串，然后将字符串转成对象，这个时候就可以给data里增加节点children
  for (var i in data) {
    if (data[i].parentId === pid) {
      //如果数据中的parentId和传进来的pid相等,把当前的数据push进一个数组里
      result.push(data[i]);
      temp = reverseTree(data,data[i]._id);
      if(temp.length>0){
        data[i].children = temp;
      }
    }
  }
  return result;
 }

 //删除分类下的新闻
 const removeNews = cateid => {
    return new Promise(resolve => {
        News.remove({path:new RegExp(cateid,'g')},(err,data) => {
          resolve(data);
        });
    });
 }

 const removeComments = cateid => {
  return new Promise(resolve => {
      Comment.remove({paths:new RegExp(cateid,'g')},(err,data) => {
        resolve(data);
      });
  });
}

//根据cateId删除评论
function removeNewsByCateIds(id) {
    return new Promise(resole => {
      let promise = Promise.all([removeComments(id),removeNews(id)]);

      promise.then(result => {
        let isDel = true;
        result.forEach(ele => { 
          if(ele.ok != 1) {
            isDel = false;
          }
        });

        resole(isDel);
      });
    })
}

